import { Fun } from '@/common/interface'
import {Message, MessageBox} from "element-ui";
import store from '@/store';
import {MessageType} from "element-ui/types/message";

export class ActionRW {
    timer: any = null
    wait = 3000
    cb: any = null
    throttle(cb: Fun) {
        this.cb = cb
        if (this.timer) clearTimeout(this.timer)
        this.timer = setTimeout(() => {
            cb()
            this.timer = null
            this.cb = null
        }, this.wait);
    }

    close() {
        clearTimeout(this.timer)
        if (this.timer && this.cb) {
            this.cb()
            this.cb = null
        }
        this.timer = null
    }
}

export const deepClone = (val) => {
    if (typeof val != 'object' || null == val) {
        return val;
    }
    const res = new val.constructor(); // TODO constructor指向不是特别安全
    for (const [key, value] of Object.entries(val)) {
        res[key] = deepClone(value);
    }
    return res;
}

export const getuuid = (): string => {
    const s: any = [];
    const hexDigits = '0123456789abcdef';
    for (let i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = '4';
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
    s[8] = s[13] = s[18] = s[23] = '-';
    return s.join('');
}

export const setOptions = (arr: any[], str: string, data: any[]) => {
    arr.forEach(e => {
        if (e.code === str) {
            e.options = data
        }
    })
}

//
// 校验审批人  主要用于流程审批  整个流程至少要有一个审批人
export function validateApprover(activityModel) {
    if (activityModel.filter(e => e.nodeType === 1).every(e => e.userList && e.userList.length == 0)) {
        Message.warning("请至少选择一个审批人");
        return false;
    }
    for (const ele of activityModel) {
        if (ele.isOwnSetting === 0 && ele.userList && ele.userList.length) {
            if (ele.userList.some((e) => e.id == -1)) {
                Message.warning("请选择人员，或删除空的节点");
                return false;
            }
        }
    }
    return true;
}

interface Prams {
    checksum?: any,
    expireTime?: any,
    materialId?: any
}
/**
 * 
 * @param { string } url 地址
 * @returns { Object } 参数对象
 */
export function getUrlParams(url): Prams {
    let str = url
    const idx = str.indexOf('?')
    const obj = {}
    if (idx !== -1) {
        str = str.slice(idx + 1)
        const arr = str.split('&')
        for (let i = 0; i < arr.length; i++) {
            const [a, b] = arr[i].split('=')
            obj[a] = b
        }
    }
    return obj
}

export function getComponent(name) {
    return (resolve) => require(['@/views' + name + '.vue'], resolve)
}

const ComponentHolder = { render: h => h("router-view") }

interface componentRoute {
    title?: string,
    index?: string,
    path?: string,
    name: string
    component?: any,
    menuType?: string,
    icon?: string
    children?: any[]
}
export const backendMenuToRoute = (menu, parent) => {
    const route: componentRoute = {
        name: ''
    }
    const { menuType } = menu
    if (menuType !== 'F') {
        route.menuType = menuType || ''
        route.name = menu.component || ''
        route.title = menu.name
        route.icon = menu.icon || ''
        route.index = String(menu.id)
        route.path = menuType === 'M' ? menu.childList[0].path.split('/')[1] : '/' + menu.component
        route.component = menuType === 'M' ? ComponentHolder : getComponent(menu.path)
    } else {
        if (parent.component) {
            store.commit('setBtnPermission', { name: parent.component, id: { id: menu.id, name: menu.name } })
        }
    }
    return route
}
/**
 * @description 绑定事件 on(element, event, handler)
 */
export const on = (function () {
    const doc: any = document
    if (doc.addEventListener) {
        return function (element, event, handler) {
            if (element && event && handler) {
                element.addEventListener(event, handler, false)
            }
        }
    } else {
        return function (element, event, handler) {
            if (element && event && handler) {
                element.attachEvent('on' + event, handler)
            }
        }
    }
})()
/**
 * @description 解绑事件 off(element, event, handler)
 */
 export const off = (function () {
    const doc: any = document
    if (doc.removeEventListener) {
      return function (element, event, handler) {
        if (element && event) {
          element.removeEventListener(event, handler, false)
        }
      }
    } else {
      return function (element, event, handler) {
        if (element && event) {
          element.detachEvent('on' + event, handler)
        }
      }
    }
  })()

export function handleCofirm(text = '确定执行此操作吗？', type:MessageType = 'warning') {
    return MessageBox.confirm(text, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: type,
    })
}